import sys
import requests
from bs4 import BeautifulSoup

def get_latest_boost_unix_release():
    # Boost官方网站的URL（请替换为实际的URL）
    # url = "https://www.boost.org/users/download/"
    url = "https://www.boost.org/releases/latest/"

    # 发送HTTP请求
    response = requests.get(url)
    response.raise_for_status()  # 如果请求失败，会抛出HTTPError异常

    # 使用BeautifulSoup解析HTML
    soup = BeautifulSoup(response.text, "html.parser")

    # 找到包含下载链接的部分（这里需要根据实际的HTML结构进行调整）
    # 假设下载链接在<a>标签中，并且有一个特定的类名或属性
    links = soup.find_all('a', href=True)

    # 遍历链接，找到Unix平台下的最新发行版压缩文件
    for link in links:
        # 根据需要调整这里的筛选条件
        if 'release' in link.get('href') and 'tar.gz' in link.get('href'):
            latest_release_url = link.get('href')
            break
    else:
        return None  # 如果没有找到符合条件的链接，返回None

    # 返回完整的下载链接
    return latest_release_url

def download_file(url, save_path):
# 发送GET请求
    response = requests.get(url, stream=True)

    # 检查响应状态
    if response.status_code == 200:
        # 打开一个文件用于保存下载的内容
        with open(save_path, 'wb') as file:
            # 从响应中逐块读取数据并写入文件
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    file.write(chunk)
                    file.flush()
        print(f"File downloaded and saved to {save_path}")
        return True
    else:
        print(f"Failed to download file. Status code: {response.status_code}")
        return False

# 设置保存文件的路径和名称
save_path = "/home/shr/MyGitee/boost-search-engine/boost-searcher/data/boost_tar_d/boost_unix_release.tar.gz"
# 保存上一次的 latest_release_url
lastUrlFile = "/home/shr/MyGitee/boost-search-engine/boost-searcher/htmlUpdate_d/lastUrl.txt"

if __name__ == "__main__":
    latest_release_url = get_latest_boost_unix_release()
    if latest_release_url:
        print(f"Latest Boost Unix release URL: {latest_release_url}")
    else:
        print("Failed to find the latest Boost Unix release.")
    
    with open(lastUrlFile, 'r') as lastUrl:
        url = lastUrl.readline()
    lastUrl.close()
    print(f"last url: {url}")
    # boost版本有所更新，进行更新
    if url == ' ' or url != latest_release_url:
        with open(lastUrlFile, 'w') as lastUrl:
            lastUrl.write(latest_release_url)
        lastUrl.close()
        if download_file(latest_release_url, save_path):
            print("download file done")
        else:
            print("download file err")
        sys.exit(1) # 进行了更新，告诉父进程
    else: #当前已是最新版本
        print("当前已是最新版本...")
        sys.exit(0) #

